local skynet     = require "skynet"
local mysql      = require "skynet.db.mysql"
local cjson      = require "cjson"
local datacenter = require "skynet.datacenter"
local template   = require "template"
local redis      = require "skynet.db.redis"


require "functions"

require "skynet.manager"

local CMD = {}
local users = {}
local db

function CMD.adduser(uid, fd)
    skynet.error("userd adduser uid=>", uid)
    users[uid] = { agent = fd }
end

function CMD.addcoin(data)
    skynet.error("userd addcoin data====>", cjson.encode(data))
    local uid = math.floor(data.id)
    local user = users[uid]

    if user then
        if user.agent then
            -- 玩家在线状态
            skynet.error("userd addcoin userid =>"..uid.." 玩家在线状态")
            pcall(skynet.call, user.agent, "lua", "addcoin", data.op, data.tp, data.num)
        end
    else
        -- 玩家离线状态
        skynet.error("userd addcoin userid =>"..uid.." 玩家离线状态")
        pcall(skynet.call,"redisd","lua","savecoin",uid,data.op, data.tp, data.num)
    end
end

skynet.start(function()
    skynet.dispatch("lua", function(session, source, cmd, ...)
        skynet.error("userd dispatch", cmd)
        local f = assert(CMD[cmd])
        skynet.ret(skynet.pack(f(...)))
    end)

    skynet.fork(function()
        while true do
            skynet.sleep(300)
        end
    end)
    skynet.register "userd"
end)
